var bookId;

function renderOptions() {
  var category = parent.getCategory();

  $('.book-category').text('');

  for (var i = 0; i < category.length; i++) {
    var op = `
      <option value="${category[i].categoryId}">${category[i].categoryName}</option>
    `
    $('.book-category').append($(op));
  }
}

// 初始化
function init() {
  renderOptions();

  bookId = location.search ? location.search.split('=')[1] : null;
  console.log(bookId);

  if (bookId) { // 编辑
    editInit();
  } else { //  新增数据
    addInit();
  }
}

function addInit() {
  $('#book-title').text('图书新增');
}

function editInit() {
  $('#book-title').text('图书编辑');

  // 查找该id所有详细信息
  var bookDetail = parent.getBookById(bookId);

  var category = parent.getCategory(); // 获取分类
  // 获取分类名
  var categoryOne = category.find(function (item) {
    return item.categoryName == bookDetail.category
  });

  $('.book-name').val(bookDetail.bookName);
  $('.book-desc').val(bookDetail.des);
  $('.book-category').val(categoryOne.categoryId);
}

init();

// 提交数据
$('#bookSubmitBtn').on('click', function () {
  var category = parent.getCategory(); // 获取分类

  var bookNameValue = $('.book-name').val();
  var bookDesc = $('.book-desc').val();
  var bookCategoryValue = $('.book-category').val();
  var time = Date.now();

  // 获取分类名
  var categoryOne = category.find(function (item) {
    return item.categoryId == bookCategoryValue
  });

  if (bookId) {
    var obj = {
      bookId: bookId,
      bookName: bookNameValue,
      time: time,
      des: bookDesc,
      category: categoryOne.categoryName
    }
    console.log(obj);
    parent.editBook(obj);
  } else {
    var obj = {
      bookId: Date.now(),
      bookName: bookNameValue,
      time: time,
      des: bookDesc,
      category: categoryOne.categoryName
    }
    console.log(obj);

    parent.addBook(obj);
  }

  layer.msg('书籍操作成功');

  var bookNameValue = $('.book-name').val('');
  var bookDesc = $('.book-desc').val('');
  var bookCategoryValue = $('.book-category').val(category[0].categoryId);
  bookId = null;
});

// 返回上一级
$('#back-btn').on('click', function () {
  history.back();
});